const fs = require('fs')
const child = require('child_process')
const packages = require('./packages')

start()

function start() {
    for (let pkg of packages) {
        processItem(pkg)
    }
}

function fileExistsSync(name, parentPath) {
    const p = combinePath(name, parentPath)
    return fs.existsSync(p)
}

function processItem(pkg, parentPath) {
    if (fileExistsSync(pkg.name, parentPath) && pkg.url) {
        console.warn(`${pkg.name}已经存在，跳过`)
    } else {
        if (pkg.skip) {
            console.warn(`skip ${pkg.name}`)
            return
        }
        if (!pkg.url) {
            if (!fileExistsSync(pkg.name, parentPath)) {
                fs.mkdirSync(combinePath(pkg.name, parentPath))
            }
            ;(pkg.children || []).forEach(p => {
                processItem(p, combinePath(pkg.name, parentPath))
            })
        } else {
            clone(pkg.url, combinePath(pkg.name, parentPath))
        }
    }
}

function combinePath(name, parentPath) {
    return (parentPath ? (parentPath + '/') : '') + name
}

function clone(url, dirName) {
    child.execFileSync('git', ['clone', url, dirName], { shell: true, encoding: 'utf-8', stdio: ['ignore', 'pipe', process.stderr]})
}